import 'dart:convert';
import 'dart:io';

import 'package:huxiaodui/api/model/mobile_app_model.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/v4.dart';


class Store{
  static late SharedPreferences prefs;
  static _Position position = _Position();
  static _Auth auth = _Auth();
  static _MobileApp mobileApp = _MobileApp();
  static _MQTT mqtt = _MQTT();

  static Future<void> init() async {

    prefs = await SharedPreferences.getInstance();

  }
  static Future<void> reload() async {
    await prefs.reload();
  }

}

class _MQTT{
  Future<String> getClientIdentifier() async{
    var appData = await Store.mobileApp.get();
    if (appData != null) {
      MobileAppModel app = MobileAppModel.fromJson(appData);
      return "login_${Platform.isAndroid ? "android" : Platform.isIOS ? "ios" : "other"}_${app.account}";
    } else {
      Store.reload();
      String? cl = Store.prefs.getString("clientIdentifier");
      if (cl == null) {
        cl = const UuidV4().generate().replaceAll("-", "");
        Store.prefs.setString("clientIdentifier", cl);
      }
      return "logout_${Platform.isAndroid ? "android" : Platform.isIOS ? "ios" : "other"}_$cl";
    }
  }
}
class _Position{
  static const String _key = "location";
  Future<void> save(Map<String,dynamic> data) async {
    await Store.prefs.setString(_key, jsonEncode(data));
  }
  Future<Map<String, dynamic>?> get() async {

    await Store.reload();
    String? data = Store.prefs.getString(_key);
    if(data!=null) return jsonDecode(data);
    return null;
  }
  Future<void> del() async {
    await Store.prefs.remove(_key);
  }
}

class _Auth{
  static const String _key = "authorization";
  Future<void> save(String data) async {
    await Store.prefs.setString(_key, data);
  }
  Future<String?> get() async {
    await Store.reload();
    String? data = Store.prefs.getString(_key);
    return data;
  }
  Future<void> del() async {
    await Store.prefs.remove(_key);
  }
}

class _MobileApp{
  static const String _key = "MobileApp";
  Future<void> save(MobileAppModel? data) async {
    if(data == null){
      del();
      return;
    }

    await Store.prefs.setString(_key, jsonEncode(data.toJson()));
  }
  Future<Map<String, dynamic>?> get() async {

    await Store.reload();
    String? data = Store.prefs.getString(_key);
    if(data!=null) return jsonDecode(data);
    return null;
  }
  Future<void> del() async {
    await Store.prefs.remove(_key);
  }
}

